package com.example.canal.model;

import com.alibaba.otter.canal.protocol.CanalEntry;
import com.example.canal.event.EventInfo;
import lombok.Data;
import org.springframework.util.CollectionUtils;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Data
public class SyncDataRowItemDTO implements Serializable {

    private String tableName;

    private String schemaName;

    private String eventType;

    private List<DataRowColumnItem> beforeValues;

    private List<DataRowColumnItem> afterValues;


    @Data
    public static class DataRowColumnItem implements Serializable {

        private String name;

        private String value;

    }

    public static SyncDataRowItemDTO buildFromRowData(EventInfo eventInfo) {
        if (Objects.isNull(eventInfo)) {
            return null;
        }
        SyncDataRowItemDTO itemDTO = new SyncDataRowItemDTO();
        itemDTO.setTableName(eventInfo.getTableInfo().getTableName());
        itemDTO.setSchemaName(eventInfo.getTableInfo().getSchemaName());
        itemDTO.setEventType(eventInfo.getEventType().name());
        CanalEntry.RowData rowData = eventInfo.getRowData();
        List<CanalEntry.Column> beforeColumnList = rowData.getBeforeColumnsList();
        if (!CollectionUtils.isEmpty(beforeColumnList)) {
            itemDTO.setBeforeValues(buildItemList(beforeColumnList));
        }
        List<CanalEntry.Column> afterColumnList = rowData.getAfterColumnsList();
        if (!CollectionUtils.isEmpty(afterColumnList)) {
            itemDTO.setAfterValues(buildItemList(afterColumnList));
        }
        return itemDTO;
    }

    private static List<DataRowColumnItem> buildItemList(List<CanalEntry.Column> beforeColumnList) {
        List<DataRowColumnItem> dataRowColumnItems = new ArrayList<>();
        for (CanalEntry.Column column : beforeColumnList) {
            DataRowColumnItem columnItem = new DataRowColumnItem();
            columnItem.setName(column.getName());
            columnItem.setValue(column.getValue());
            dataRowColumnItems.add(columnItem);
        }
        return dataRowColumnItems;
    }

}
